# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
 -------------------------------------------------
    File Name:     decorators.py
    Description:   装饰器工具集
 -------------------------------------------------
 """
import functools
import time
from typing import Callable


def retry(max_attempts: int = 3, delay: float = 1.0):
    """
    重试装饰器

    :param max_attempts: 最大重试次数
    :param delay: 重试间隔时间(秒)
    """

    def decorator(func: Callable):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            attempts = 0
            while attempts < max_attempts:
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    attempts += 1
                    if attempts == max_attempts:
                        raise e
                    print(f"执行失败，正在进行第{attempts}次重试...")
                    time.sleep(delay)
            return None

        return wrapper

    return decorator


def timer(func: Callable):
    """
    计时装饰器
    """

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"函数 {func.__name__} 执行时间: {end_time - start_time:.2f} 秒")
        return result

    return wrapper


def log_action(message: str = None):
    """
    操作日志装饰器
    :param message: 自定义日志消息
    """

    def decorator(func: Callable):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            func_name = func.__name__
            print(f"开始执行: {message or func_name}")
            try:
                result = func(*args, **kwargs)
                print(f"执行完成: {message or func_name}")
                return result
            except Exception as e:
                print(f"执行失败: {message or func_name}, 错误信息: {str(e)}")
                raise

        return wrapper

    return decorator
